<?php 
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use backend\models\Log;
use backend\models\Time;
use backend\models\Admin;

class LogController extends Controller{

	public $layout = 'common';
	public function init()
    {
    	parent::init();
    	$session = Yii::$app->session;
    	$session->open();
    	$data=Yii::$app->request->get()['r'];
		// echo $data;die;
		if($data!='login/index')
		{
			if(!isset($_SESSION['user'])){
            echo "<script>alert('请先登录');location.href='?r=login/index'</script>";
        	}
        }
    }
	public function actionIndex()
	{
		if($log_content = Yii::$app->request->post('content'))
		{
			$data=Yii::$app->request->post();
			$log_content=$log_content;
			$log_time=date('Y-m-d');
			$time=Time::find()->where(['lo_time'=>$log_time])->one();
			// print_r($time);die;
			if(!$time)
			{
				$time=new Time;
				$time->lo_time=$log_time;
				if($time->insert())
				{
					$t_id=Yii::$app->db->getLastInsertID();
					$admin_id=$_SESSION['user']['admin_id'];
					$log=new Log;
					$log->admin_id=$admin_id;
					$log->log_content=$log_content;
					$log->t_id=$t_id;
					if($log->insert())
					{
						echo "<script>alert('添加成功');location.href='?r=log/show'</script>";
					}else{
						echo "<script>alert('添加失败');location.href='?r=log/index'</script>";
					}
				}
			}else{
				$t_id=$time['t_id'];
				// echo $t_id;die;
				$admin_id=$_SESSION['user']['admin_id'];
				$sql = "INSERT INTO e_log VALUES (NULL,:adminid,:content,:tid)";
				$res = Yii::$app->db->createCommand($sql,[':adminid'=>$admin_id,':content'=>$log_content,':tid'=>$t_id])->query();
				if($res)
				{
					echo "<script>alert('添加成功');location.href='?r=log/show'</script>";
				}else{
					echo "<script>alert('添加失败');location.href='?r=log/index'</script>";
				}
			}
			
		}else{
		$model=new Log;
		return $this->render('index',['model'=>$model]);
		}
	}

	public function actionShow()
	{
		$time=Yii::$app->db->createCommand('SELECT * FROM e_time ORDER BY t_id DESC')->queryAll();
		// var_dump($time);
		// die;
		foreach($time as $key => $val)
		{
			
			$time[$key]['c_time']=Yii::$app->db->createCommand("SELECT * FROM e_log where t_id=".$val['t_id']." ORDER BY log_id DESC")->query();
		}
		// echo $c_time;die;
		// print_r($time)
		// print_r($_SESSION['user']);die;
		if(empty($_SESSION['user']))
		{
			return $this->render('show',['time'=>$time]);
		}else{
			return $this->render('show',['time'=>$time,'session'=>$_SESSION['user']]);
		}
		

	}

}

 ?>
